package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.*;
import com.demo.youxuanmall.mapper.OrderItemMapper;
import com.demo.youxuanmall.mapper.OrderMapper;
import com.demo.youxuanmall.service.AddressService;
import com.demo.youxuanmall.service.CartService;
import com.demo.youxuanmall.service.OrderService;
import com.demo.youxuanmall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private AddressService addressService;
    
    @Override
    @Transactional
    public Result<Order> createOrder(Long userId, Long shippingId) {
        // 校验参数
        if (userId == null || shippingId == null) {
            return Result.error("参数错误");
        }
        
        // 获取用户购物车中选中的商品
        Result<List<Cart>> cartResult = cartService.listUserCarts(userId);
        if (cartResult.getCode() != 0 || cartResult.getData() == null) {
            return Result.error("获取购物车失败");
        }
        
        List<Cart> cartList = cartResult.getData().stream()
                .filter(cart -> cart.getChecked() != null && cart.getChecked() == 1)
                .collect(Collectors.toList());
        
        if (cartList.isEmpty()) {
            return Result.error("购物车中没有选中的商品");
        }
        
        // 获取收货地址
        Address address = addressService.getById(shippingId);
        if (address == null || !address.getUserId().equals(userId)) {
            return Result.error("收货地址不存在");
        }
        
        // 生成订单号
        String orderNo = generateOrderNo();
        
        // 计算订单总金额
        BigDecimal totalAmount = new BigDecimal("0");
        List<OrderItem> orderItems = new ArrayList<>();
        
        for (Cart cart : cartList) {
            Product product = productService.getById(cart.getProductId());
            if (product == null || product.getStatus() != 1) {
                return Result.error("商品" + (product != null ? product.getName() : "") + "已下架");
            }
            
            if (product.getStock() < cart.getQuantity()) {
                return Result.error("商品" + product.getName() + "库存不足");
            }
            
            // 扣减库存
            product.setStock(product.getStock() - cart.getQuantity());
            product.setSales(product.getSales() + cart.getQuantity());
            productService.updateById(product);
            
            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setUserId(userId);
            orderItem.setOrderNo(orderNo);
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentPrice(product.getPrice());
            orderItem.setQuantity(cart.getQuantity());
            orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(cart.getQuantity())));
            
            orderItems.add(orderItem);
            totalAmount = totalAmount.add(orderItem.getTotalPrice());
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        order.setPayment(totalAmount);
        order.setPaymentType(1); // 在线支付
        order.setPostage(new BigDecimal("0")); // 暂时不计算邮费
        order.setStatus(10); // 未付款
        
        // 保存订单
        save(order);
        
        // 保存订单项
        for (OrderItem orderItem : orderItems) {
            orderItemMapper.insert(orderItem);
        }
        
        // 清空购物车中已下单的商品
        for (Cart cart : cartList) {
            cartService.removeById(cart.getId());
        }
        
        // 查询完整的订单信息
        order.setShippingAddress(address);
        order.setOrderItems(orderItems);
        
        return Result.success(order);
    }
    
    @Override
    public Result<Order> getOrderDetail(Long userId, String orderNo) {
        if (orderNo == null) {
            return Result.error("参数错误");
        }
        
        try {
            // 查询订单基本信息
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getOrderNo, orderNo);
            // 如果是用户查询，需要验证用户ID
            if (userId != null) {
                wrapper.eq(Order::getUserId, userId);
            }
            Order order = getOne(wrapper);
        
        if (order == null) {
            return Result.error("订单不存在");
        }
            
            // 设置订单状态描述
            setOrderStatusDesc(order);
        
            // 一次性查询所有订单项
        LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(OrderItem::getOrderNo, orderNo);
        List<OrderItem> orderItems = orderItemMapper.selectList(itemWrapper);
            if (orderItems != null) {
            order.setOrderItems(orderItems);
            } else {
                order.setOrderItems(Collections.emptyList());
            }
        
        // 查询收货地址
            if (order.getShippingId() != null) {
        Address address = addressService.getById(order.getShippingId());
                if (address != null) {
        order.setShippingAddress(address);
                }
            }
        
        return Result.success(order);
        } catch (Exception e) {
            log.error("查询订单详情异常: userId={}, orderNo={}", userId, orderNo, e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<Order>> listUserOrders(Long userId, Integer pageNum, Integer pageSize) {
        if (userId == null || pageNum == null || pageSize == null) {
            return Result.error("参数错误");
        }
        
        // 添加合理性检查
        if (pageNum <= 0 || pageSize <= 0 || pageSize > 20) {
            return Result.error("分页参数错误: 页码和每页大小必须为正数，且每页大小不能超过20");
        }
        
        try {
            // 使用MP提供的分页查询
        Page<Order> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
                .orderByDesc(Order::getCreateTime);
        
            // 执行分页查询
        Page<Order> orderPage = page(page, wrapper);
        
            if (orderPage.getRecords() != null && !orderPage.getRecords().isEmpty()) {
                // 收集所有订单号，批量查询订单项
                List<String> orderNos = orderPage.getRecords().stream()
                    .map(Order::getOrderNo)
                    .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orderPage.getRecords().stream()
                    .map(Order::getShippingId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
                
                try {
                    // 批量查询订单项
            LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                    itemWrapper.in(OrderItem::getOrderNo, orderNos);
                    List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                    
                    // 按订单号分组
                    Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                        .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                    
                    // 批量查询收货地址
                    Map<Long, Address> addressMap = Collections.emptyMap();
                    if (!addressIds.isEmpty()) {
                        List<Address> addresses = addressService.listByIds(addressIds);
                        addressMap = addresses.stream()
                            .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                    }
                    
                    // 设置订单详情
                    Map<Long, Address> finalAddressMap = addressMap;
                    orderPage.getRecords().forEach(order -> {
                        // 设置订单状态描述
                        setOrderStatusDesc(order);
                        
                        // 设置订单项
                        order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
                    
                        // 设置收货地址
                    if (order.getShippingId() != null) {
                            order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                    });
                } catch (Exception e) {
                    log.error("批量查询订单项或地址异常: {}", e.getMessage(), e);
                    // 不要阻断主流程，返回部分数据
                    // 设置基本订单状态描述
                    orderPage.getRecords().forEach(this::setOrderStatusDesc);
                }
            }
            
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("查询用户订单异常: userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize, e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<Order>> listUserOrdersByStatus(Long userId, Integer status, Integer pageNum, Integer pageSize) {
        if (userId == null || status == null || pageNum == null || pageSize == null) {
            return Result.error("参数错误");
        }
        
        // 添加合理性检查
        if (pageNum <= 0 || pageSize <= 0 || pageSize > 20) {
            return Result.error("分页参数错误: 页码和每页大小必须为正数，且每页大小不能超过20");
        }
        
        // 检查状态是否有效
        if (status != 10 && status != 20 && status != 30 && status != 40 && status != 50) {
            return Result.error("订单状态参数错误");
        }
        
        try {
            // 使用MP提供的分页查询
            Page<Order> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getUserId, userId)
                   .eq(Order::getStatus, status)
                   .orderByDesc(Order::getCreateTime);
            
            // 执行分页查询
            Page<Order> orderPage = page(page, wrapper);
            
            if (orderPage.getRecords() != null && !orderPage.getRecords().isEmpty()) {
                // 收集所有订单号，批量查询订单项
                List<String> orderNos = orderPage.getRecords().stream()
                    .map(Order::getOrderNo)
                    .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orderPage.getRecords().stream()
                    .map(Order::getShippingId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
                
                try {
                    // 批量查询订单项
                    LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                    itemWrapper.in(OrderItem::getOrderNo, orderNos);
                    List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                    
                    // 按订单号分组
                    Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                        .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                    
                    // 批量查询收货地址
                    Map<Long, Address> addressMap = Collections.emptyMap();
                    if (!addressIds.isEmpty()) {
                        List<Address> addresses = addressService.listByIds(addressIds);
                        addressMap = addresses.stream()
                            .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                    }
                    
                    // 设置订单详情
                    Map<Long, Address> finalAddressMap = addressMap;
                    orderPage.getRecords().forEach(order -> {
                        // 设置订单状态描述
                        setOrderStatusDesc(order);
                        
                        // 设置订单项
                        order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
                    
                        // 设置收货地址
                    if (order.getShippingId() != null) {
                            order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                    });
                } catch (Exception e) {
                    log.error("批量查询订单项或地址异常: {}", e.getMessage(), e);
                    // 不要阻断主流程，返回部分数据
                    // 设置基本订单状态描述
                    orderPage.getRecords().forEach(this::setOrderStatusDesc);
                }
        }
        
        return Result.success(orderPage);
        } catch (Exception e) {
            log.error("按状态查询用户订单异常: userId={}, status={}, pageNum={}, pageSize={}", userId, status, pageNum, pageSize, e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置订单状态描述
     */
    private void setOrderStatusDesc(Order order) {
        if (order.getStatus() == null) return;
        
        switch (order.getStatus()) {
            case 10:
                order.setStatusDesc("未付款");
                break;
            case 20:
                order.setStatusDesc("已付款待发货");
                break;
            case 30:
                order.setStatusDesc("已发货");
                break;
            case 40:
                order.setStatusDesc("已完成");
                break;
            case 50:
                order.setStatusDesc("已取消");
                break;
            default:
                order.setStatusDesc("未知状态");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> cancelOrder(Long userId, String orderNo) {
        if (userId == null || orderNo == null) {
            return Result.error("参数错误");
        }
        
        // 查询订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
                .eq(Order::getOrderNo, orderNo);
        Order order = getOne(wrapper);
        
        if (order == null) {
            return Result.error("订单不存在");
        }
        
        // 检查订单状态是否允许取消
        // 状态10:未付款 状态20:已付款待发货
        if (order.getStatus() != 10 && order.getStatus() != 20) {
            String statusDesc = "";
            switch (order.getStatus()) {
                case 30: statusDesc = "已发货"; break;
                case 40: statusDesc = "已完成"; break;
                case 50: statusDesc = "已取消"; break;
                default: statusDesc = "未知状态"; break;
            }
            return Result.error("订单状态为" + statusDesc + "，不允许取消");
        }
        
        // 修改订单状态
        order.setStatus(50); // 已取消
        order.setCloseTime(LocalDateTime.now());
        updateById(order);
        
        // 记录订单状态变更日志
        log.info("订单[{}]已被用户[{}]取消，原状态: {}", orderNo, userId, 
                order.getStatus() == 10 ? "未付款" : "已付款待发货");
        
        // 恢复库存
        LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
        itemWrapper.eq(OrderItem::getOrderNo, orderNo);
        List<OrderItem> orderItems = orderItemMapper.selectList(itemWrapper);
        
        for (OrderItem orderItem : orderItems) {
            Product product = productService.getById(orderItem.getProductId());
            if (product != null) {
                product.setStock(product.getStock() + orderItem.getQuantity());
                product.setSales(product.getSales() - orderItem.getQuantity());
                productService.updateById(product);
                log.info("商品[{}]库存已恢复: +{}，销量: -{}", 
                    product.getId(), orderItem.getQuantity(), orderItem.getQuantity());
            }
        }
        
        // 如果是已付款订单取消，需要生成退款记录(TODO: 对接实际支付系统)
        if (order.getStatus() == 20) {
            // 这里仅做标记，实际项目中需要对接支付系统进行退款操作
            log.info("订单[{}]需要退款处理，金额: {}", orderNo, order.getPayment());
        }
        
        return Result.success();
    }
    
    @Override
    @Transactional
    public Result<Void> payOrder(Long userId, String orderNo) {
        if (userId == null || orderNo == null) {
            return Result.error("参数错误");
        }
        
        // 查询订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
                .eq(Order::getOrderNo, orderNo);
        Order order = getOne(wrapper);
        
        if (order == null) {
            return Result.error("订单不存在");
        }
        
        if (order.getStatus() != 10) {
            return Result.error("订单状态不正确");
        }
        
        // 修改订单状态
        order.setStatus(20); // 已付款待发货
        order.setPaymentTime(LocalDateTime.now());
        updateById(order);
        
        return Result.success();
    }
    
    @Override
    public Result<Page<Order>> listAllOrders(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            return Result.error("参数错误");
        }
        
        try {
            // 使用MP提供的分页查询
        Page<Order> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Order::getCreateTime);
        
            // 执行分页查询
        Page<Order> orderPage = page(page, wrapper);
        
            if (orderPage.getRecords() != null && !orderPage.getRecords().isEmpty()) {
                // 收集所有订单号，批量查询订单项
                List<String> orderNos = orderPage.getRecords().stream()
                    .map(Order::getOrderNo)
                    .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orderPage.getRecords().stream()
                    .map(Order::getShippingId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
                
                // 批量查询订单项
                LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.in(OrderItem::getOrderNo, orderNos);
                List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                
                // 按订单号分组
                Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                
                // 批量查询收货地址
                Map<Long, Address> addressMap = Collections.emptyMap();
                if (!addressIds.isEmpty()) {
                    List<Address> addresses = addressService.listByIds(addressIds);
                    addressMap = addresses.stream()
                        .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                }
                
                // 设置订单详情
                Map<Long, Address> finalAddressMap = addressMap;
                orderPage.getRecords().forEach(order -> {
                    // 设置订单状态描述
                    setOrderStatusDesc(order);
                    
                    // 设置订单项
                    order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
            
                    // 设置收货地址
                    if (order.getShippingId() != null) {
                        order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                });
        }
        
        return Result.success(orderPage);
        } catch (Exception e) {
            log.error("查询所有订单异常", e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<Order>> listAllOrdersByStatus(Integer status, Integer pageNum, Integer pageSize) {
        if (status == null || pageNum == null || pageSize == null) {
            return Result.error("参数错误");
        }
        
        try {
            // 使用MP提供的分页查询
            Page<Order> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getStatus, status)
                  .orderByDesc(Order::getCreateTime);
            
            // 执行分页查询
            Page<Order> orderPage = page(page, wrapper);
            
            if (orderPage.getRecords() != null && !orderPage.getRecords().isEmpty()) {
                // 收集所有订单号，批量查询订单项
                List<String> orderNos = orderPage.getRecords().stream()
                    .map(Order::getOrderNo)
                    .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orderPage.getRecords().stream()
                    .map(Order::getShippingId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
                
                // 批量查询订单项
                LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.in(OrderItem::getOrderNo, orderNos);
                List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                
                // 按订单号分组
                Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                
                // 批量查询收货地址
                Map<Long, Address> addressMap = Collections.emptyMap();
                if (!addressIds.isEmpty()) {
                    List<Address> addresses = addressService.listByIds(addressIds);
                    addressMap = addresses.stream()
                        .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                }
                
                // 设置订单详情
                Map<Long, Address> finalAddressMap = addressMap;
                orderPage.getRecords().forEach(order -> {
                    // 设置订单状态描述
                    setOrderStatusDesc(order);
                    
                    // 设置订单项
                    order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
                    
                    // 设置收货地址
                    if (order.getShippingId() != null) {
                        order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                });
            }
            
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("按状态查询所有订单异常: status={}", status, e);
            return Result.error("查询订单失败: " + e.getMessage());
        }
    }
    
    @Override
    public Result<Page<Order>> searchOrders(String keyword, Integer status, Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageSize == null) {
            return Result.error("参数错误");
        }
        
        if (keyword == null || keyword.trim().isEmpty()) {
            // 如果关键词为空，则根据状态查询
            if (status != null) {
                return listAllOrdersByStatus(status, pageNum, pageSize);
            } else {
                return listAllOrders(pageNum, pageSize);
            }
        }
        
        try {
            // 使用MP提供的分页查询
            Page<Order> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            
            // 添加查询条件
            wrapper.like(Order::getOrderNo, keyword);
            
            // 如果状态不为空，添加状态查询条件
            if (status != null) {
                wrapper.eq(Order::getStatus, status);
            }
            
            wrapper.orderByDesc(Order::getCreateTime);
            
            // 执行分页查询
            Page<Order> orderPage = page(page, wrapper);
            
            if (orderPage.getRecords() != null && !orderPage.getRecords().isEmpty()) {
                // 收集所有订单号，批量查询订单项
                List<String> orderNos = orderPage.getRecords().stream()
                    .map(Order::getOrderNo)
                    .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orderPage.getRecords().stream()
                    .map(Order::getShippingId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
                
                // 批量查询订单项
                LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.in(OrderItem::getOrderNo, orderNos);
                List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                
                // 按订单号分组
                Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                
                // 批量查询收货地址
                Map<Long, Address> addressMap = Collections.emptyMap();
                if (!addressIds.isEmpty()) {
                    List<Address> addresses = addressService.listByIds(addressIds);
                    addressMap = addresses.stream()
                        .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                }
                
                // 设置订单详情
                Map<Long, Address> finalAddressMap = addressMap;
                orderPage.getRecords().forEach(order -> {
                    // 设置订单状态描述
                    setOrderStatusDesc(order);
                    
                    // 设置订单项
                    order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
                    
                    // 设置收货地址
                    if (order.getShippingId() != null) {
                        order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                });
            }
            
            return Result.success(orderPage);
        } catch (Exception e) {
            log.error("搜索订单异常: keyword={}, status={}", keyword, status, e);
            return Result.error("搜索订单失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> shipOrder(String orderNo) {
        if (orderNo == null) {
            return Result.error("参数错误");
        }
        
        // 查询订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo, orderNo);
        Order order = getOne(wrapper);
        
        if (order == null) {
            return Result.error("订单不存在");
        }
        
        if (order.getStatus() != 20) {
            return Result.error("订单状态不正确");
        }
        
        // 修改订单状态
        order.setStatus(30); // 已发货
        order.setSendTime(LocalDateTime.now());
        updateById(order);
        
        return Result.success();
    }
    
    @Override
    public Result<Integer[]> getOrderStats() {
        // 分别统计各状态订单数量：未付款, 已付款待发货, 已发货, 已完成, 已取消
        Integer[] stats = new Integer[5];
        
        LambdaQueryWrapper<Order> wrapper10 = new LambdaQueryWrapper<>();
        wrapper10.eq(Order::getStatus, 10);
        stats[0] = (int)count(wrapper10);
        
        LambdaQueryWrapper<Order> wrapper20 = new LambdaQueryWrapper<>();
        wrapper20.eq(Order::getStatus, 20);
        stats[1] = (int)count(wrapper20);
        
        LambdaQueryWrapper<Order> wrapper30 = new LambdaQueryWrapper<>();
        wrapper30.eq(Order::getStatus, 30);
        stats[2] = (int)count(wrapper30);
        
        LambdaQueryWrapper<Order> wrapper40 = new LambdaQueryWrapper<>();
        wrapper40.eq(Order::getStatus, 40);
        stats[3] = (int)count(wrapper40);
        
        LambdaQueryWrapper<Order> wrapper50 = new LambdaQueryWrapper<>();
        wrapper50.eq(Order::getStatus, 50);
        stats[4] = (int)count(wrapper50);
        
        return Result.success(stats);
    }
    
    @Override
    @Transactional
    public Result<Void> confirmOrder(Long userId, String orderNo) {
        if (userId == null || orderNo == null) {
            return Result.error("参数错误");
        }
        
        // 查询订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId)
                .eq(Order::getOrderNo, orderNo);
        Order order = getOne(wrapper);
        
        if (order == null) {
            return Result.error("订单不存在");
        }
        
        if (order.getStatus() != 30) {
            return Result.error("订单状态不正确，无法确认收货");
        }
        
        // 修改订单状态
        order.setStatus(40); // 已完成
        order.setEndTime(LocalDateTime.now());
        updateById(order);
        
        return Result.success();
    }
    
    /**
     * 生成订单号
     * 规则：年月日时分秒 + 4位随机数
     */
    private String generateOrderNo() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String dateTime = LocalDateTime.now().format(formatter);
        
        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000);
        String randomStr = String.format("%04d", randomNum);
        
        return dateTime + randomStr;
    }
    
    @Override
    public Map<String, Object> getStatisticsData(String startDate, String endDate) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取概览数据
            // 总订单数
            Long totalOrders = baseMapper.selectCount(null);
            
            // 待处理订单数
            Integer pendingOrders = baseMapper.countOrdersByStatus(0); // 待付款
            Integer processingOrders = baseMapper.countOrdersByStatus(1); // 待发货
            
            // 总销售额
            BigDecimal totalSales = baseMapper.getTotalSales();
            
            // 订单状态分布
            Map<String, Integer> orderStatus = new HashMap<>();
            orderStatus.put("pending", baseMapper.countOrdersByStatus(0)); // 待付款
            orderStatus.put("processing", baseMapper.countOrdersByStatus(1)); // 待发货
            orderStatus.put("shipped", baseMapper.countOrdersByStatus(2)); // 待收货
            orderStatus.put("completed", baseMapper.countOrdersByStatus(3)); // 已完成
            orderStatus.put("cancelled", baseMapper.countOrdersByStatus(4)); // 已取消
            
            // 销售趋势
            List<Map<String, Object>> salesTrend = baseMapper.getSalesTrendByDay(startDate, endDate);
            
            // 封装数据
            result.put("totalOrders", totalOrders);
            result.put("pendingOrders", pendingOrders);
            result.put("processingOrders", processingOrders);
            result.put("totalSales", totalSales);
            result.put("orderStatus", orderStatus);
            result.put("salesTrend", salesTrend);
            
            return result;
        } catch (Exception e) {
            log.error("获取订单统计数据出错", e);
            return new HashMap<>();
        }
    }
    
    @Override
    public List<Order> getRecentOrders(Long userId, int limit) {
        if (userId == null || limit <= 0) {
            return Collections.emptyList();
        }
        
        try {
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getUserId, userId)
                   .orderByDesc(Order::getCreateTime)
                   .last("LIMIT " + limit);
            
            List<Order> orders = list(wrapper);
            
            if (orders != null && !orders.isEmpty()) {
                // 收集所有订单号
                List<String> orderNos = orders.stream()
                        .map(Order::getOrderNo)
                        .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orders.stream()
                        .map(Order::getShippingId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                
                // 批量查询订单项
                LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.in(OrderItem::getOrderNo, orderNos);
                List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                
                // 按订单号分组
                Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                        .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                
                // 批量查询收货地址
                Map<Long, Address> addressMap = Collections.emptyMap();
                if (!addressIds.isEmpty()) {
                    List<Address> addresses = addressService.listByIds(addressIds);
                    addressMap = addresses.stream()
                            .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                }
                
                // 设置订单详情
                Map<Long, Address> finalAddressMap = addressMap;
                orders.forEach(order -> {
                    // 设置订单状态描述
                    setOrderStatusDesc(order);
                    
                    // 设置订单项
                    order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
                    
                    // 设置收货地址
                    if (order.getShippingId() != null) {
                        order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                });
            }
            
            return orders;
        } catch (Exception e) {
            log.error("查询用户最近订单异常: userId={}, limit={}", userId, limit, e);
            return Collections.emptyList();
        }
    }
    
    @Override
    public List<Order> getUserOrders(Long userId) {
        if (userId == null) {
            return Collections.emptyList();
        }
        
        try {
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getUserId, userId)
                   .orderByDesc(Order::getCreateTime);
            
            List<Order> orders = list(wrapper);
            
            if (orders != null && !orders.isEmpty()) {
                // 收集所有订单号
                List<String> orderNos = orders.stream()
                        .map(Order::getOrderNo)
                        .collect(Collectors.toList());
                
                // 收集所有收货地址ID
                List<Long> addressIds = orders.stream()
                        .map(Order::getShippingId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                
                // 批量查询订单项
                LambdaQueryWrapper<OrderItem> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.in(OrderItem::getOrderNo, orderNos);
                List<OrderItem> allOrderItems = orderItemMapper.selectList(itemWrapper);
                
                // 按订单号分组
                Map<String, List<OrderItem>> orderItemsMap = allOrderItems.stream()
                        .collect(Collectors.groupingBy(OrderItem::getOrderNo));
                
                // 批量查询收货地址
                Map<Long, Address> addressMap = Collections.emptyMap();
                if (!addressIds.isEmpty()) {
                    List<Address> addresses = addressService.listByIds(addressIds);
                    addressMap = addresses.stream()
                            .collect(Collectors.toMap(Address::getId, Function.identity(), (a1, a2) -> a1));
                }
                
                // 设置订单详情
                Map<Long, Address> finalAddressMap = addressMap;
                orders.forEach(order -> {
                    // 设置订单状态描述
                    setOrderStatusDesc(order);
                    
                    // 设置订单项
                    order.setOrderItems(orderItemsMap.getOrDefault(order.getOrderNo(), Collections.emptyList()));
                    
                    // 设置收货地址
                    if (order.getShippingId() != null) {
                        order.setShippingAddress(finalAddressMap.get(order.getShippingId()));
                    }
                });
            }
            
            return orders;
        } catch (Exception e) {
            log.error("查询用户订单异常: userId={}", userId, e);
            return Collections.emptyList();
        }
    }
    
    @Override
    @Transactional
    public Result<Order> createOrderFromProduct(Long userId, Long productId, Integer quantity) {
        // 校验参数
        if (userId == null || productId == null || quantity == null || quantity <= 0) {
            return Result.error("参数错误");
        }
        
        // 获取商品信息
        Product product = productService.getById(productId);
        if (product == null || product.getStatus() != 1) {
            return Result.error("商品已下架");
        }
        
        if (product.getStock() < quantity) {
            return Result.error("商品库存不足");
        }
        
        // 获取用户默认收货地址
        List<Address> addresses = addressService.getUserAddresses(userId);
        if (addresses.isEmpty()) {
            return Result.error("请先添加收货地址");
        }
        
        // 使用第一个地址作为默认地址
        Address address = addresses.get(0);
        
        // 生成订单号
        String orderNo = generateOrderNo();
        
        // 创建订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setUserId(userId);
        orderItem.setOrderNo(orderNo);
        orderItem.setProductId(product.getId());
        orderItem.setProductName(product.getName());
        orderItem.setProductImage(product.getMainImage());
        orderItem.setCurrentPrice(product.getPrice());
        orderItem.setQuantity(quantity);
        orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(quantity)));
        
        // 扣减库存
        product.setStock(product.getStock() - quantity);
        product.setSales(product.getSales() + quantity);
        productService.updateById(product);
        
        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setShippingId(address.getId());
        order.setPayment(orderItem.getTotalPrice());
        order.setPaymentType(1); // 在线支付
        order.setPostage(new BigDecimal("0")); // 暂时不计算邮费
        order.setStatus(10); // 未付款
        
        // 保存订单
        save(order);
        
        // 保存订单项
        orderItemMapper.insert(orderItem);
        
        // 设置订单详情
        order.setShippingAddress(address);
        order.setOrderItems(Collections.singletonList(orderItem));
        
        return Result.success(order);
    }
} 